package com.th.basemodel.utils

import android.annotation.SuppressLint
import android.app.ActivityManager
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.graphics.Point
import android.net.ConnectivityManager
import android.net.wifi.WifiManager
import android.os.BatteryManager
import android.os.Build
import android.os.Environment
import android.os.StatFs
import android.telephony.SubscriptionManager
import android.telephony.TelephonyManager
import android.view.WindowManager
import java.io.File
import java.net.NetworkInterface
import java.net.SocketException


class SceneDeviceInformation {

    fun upload(context: Context): MutableMap<String, Any> {
        return mutableMapOf<String, Any>().run {
            put("strong", bettary(context))
            put("supporting", Build.BRAND)
            put("gratitude", carrier(context))
            put("neighbors", Build.MODEL)
            put("baer", imei(context))
            put("ravit", ip())
            put("israel", is_root())
            put("generall", is_simulator())
            put("advocating", mac(context))
            put("mankind", memory(context))
            put("future", "android")
            put("shared", Build.VERSION.RELEASE)
            put("community", 0)
            put("interpretation", resolution(context))
            put("enecs", 0)
            put("ceremony", sdcard())
            put("opening", storage())
            put("speech", unuse_sdcard())
            put("jian", unuse_storage())
            put("chen", wifi(context))
            put("curator", wifi_name(context))
            this
        }
    }

    private fun wifi_name(context: Context): String {
        try {
            val connectivityManager =
                context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager?
            val networkInfo = connectivityManager!!.activeNetworkInfo
            if (networkInfo != null && networkInfo.type == ConnectivityManager.TYPE_WIFI && networkInfo.isConnected) {
                val wifiManager =
                    context.applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager
                val wifiInfo = wifiManager.connectionInfo
                return wifiInfo.ssid.replace("^\"|\"$".toRegex(), "")
            }
            return ""
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return ""
    }

    private fun wifi(context: Context): Int {
        try {
            val connectivityManager =
                context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager?
            val networkInfo = connectivityManager!!.activeNetworkInfo
            return if (networkInfo != null && networkInfo.type == ConnectivityManager.TYPE_WIFI && networkInfo.isConnected) {
                1
            } else {
                0
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return 0
    }

    private fun unuse_storage(): String {
        try {
            val internalStorageDir = Environment.getDataDirectory()
            val statFs = StatFs(internalStorageDir.path)
            val blockSize = statFs.blockSizeLong
            val availableBlocks = statFs.availableBlocksLong
            return formatMemorySize(blockSize * availableBlocks)
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return ""
    }

    private fun unuse_sdcard(): String {
        try {
            return if (Environment.getExternalStorageState() == Environment.MEDIA_MOUNTED) {
                val sdCardDir = Environment.getExternalStorageDirectory()
                val statFs = StatFs(sdCardDir.path)
                val blockSize = statFs.blockSizeLong
                val availableBlocks = statFs.availableBlocksLong
                formatMemorySize(blockSize * availableBlocks)
            } else {
                ""
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return ""
    }


    private fun storage(): String {
        try {
            val internalStorageDir = Environment.getDataDirectory()
            val statFs = StatFs(internalStorageDir.path)
            val blockSize = statFs.blockSizeLong
            val totalBlocks = statFs.blockCountLong
            return formatMemorySize(blockSize * totalBlocks)
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return ""
    }

    private fun sdcard(): String {
        return try {
            val externalStorageFile = Environment.getExternalStorageDirectory()
            val statFs = StatFs(externalStorageFile.path)
            val blockSize = statFs.blockSizeLong
            val totalBlocks = statFs.blockCountLong
            val totalSize = totalBlocks * blockSize
            formatMemorySize(totalSize)
        } catch (e: Exception) {
            e.printStackTrace()
            ""
        }
    }

    private fun resolution(context: Context): String {
        try {
            val windowManager = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager?
            val display = windowManager!!.defaultDisplay
            val screenSize = Point()
            display.getSize(screenSize)
            return "${screenSize.x}x${screenSize.y}"
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return ""
    }

    private fun memory(context: Context): String {
        try {
            val memoryInfo = ActivityManager.MemoryInfo()
            val activityManager =
                context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager?
            activityManager!!.getMemoryInfo(memoryInfo)
            return formatMemorySize(memoryInfo.totalMem)
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return ""
    }

    private fun formatMemorySize(bytes: Long): String {
        val kilobytes = bytes / 1024.0
        val megabytes = kilobytes / 1024
        val gigabytes = megabytes / 1024
        return "${String.format("%.2f", gigabytes)}GB"
    }

    @SuppressLint("HardwareIds")
    private fun mac(context: Context): String {
        try {
            val wifiInfo =
                (context.applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager).connectionInfo
            return wifiInfo.macAddress
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return ""
    }

    private fun is_simulator(): Int {
        try {
            val is_simulator = (Build.FINGERPRINT.startsWith("generic")
                    || Build.FINGERPRINT.startsWith("unknown")
                    || Build.MODEL.contains("google_sdk")
                    || Build.MODEL.contains("Emulator")
                    || Build.MODEL.contains("Android SDK built for x86")
                    || Build.MANUFACTURER.contains("Genymotion")
                    || (Build.BRAND.startsWith("generic") && Build.DEVICE.startsWith("generic"))
                    || "google_sdk".equals(Build.PRODUCT))

            return if (is_simulator) {
                1
            } else {
                0
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return 0
    }

    private fun is_root(): Int {
        val suBinaryLocations = arrayOf("/sbin/su", "/system/bin/su", "/system/xbin/su")
        for (suBinaryLocation in suBinaryLocations) {
            if (File(suBinaryLocation).exists()) {
                return 1
            }
        }
        return 0
    }

    private fun ip(): String {
        try {
            val interfaces = NetworkInterface.getNetworkInterfaces()
            while (interfaces.hasMoreElements()) {
                val networkInterface = interfaces.nextElement()
                val addresses = networkInterface.inetAddresses
                while (addresses.hasMoreElements()) {
                    val address = addresses.nextElement()
                    if (!address.isLoopbackAddress && address.hostAddress.indexOf(':') == -1) {
                        return address.hostAddress
                    }
                }
            }
        } catch (e: SocketException) {
            e.printStackTrace()
        }
        return ""
    }

    private fun imei(context: Context): String {
        return try {
            val telephonyManager =
                context.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager?
            telephonyManager!!.imei
        } catch (e: Exception) {
            e.printStackTrace()
            ""
        }
    }

    private fun bettary(context: Context): String {
        try {
            // 注册电池状态广播接收器
            val intentFilter = IntentFilter(Intent.ACTION_BATTERY_CHANGED)
            val batteryStatus: Intent? = context.registerReceiver(null, intentFilter)

            // 获取当前电量百分比小数
            val level = batteryStatus?.getIntExtra(BatteryManager.EXTRA_LEVEL, -1) ?: 10
            val scale = batteryStatus?.getIntExtra(BatteryManager.EXTRA_SCALE, -1) ?: 1

            return (level * 100 / scale).toString()
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return 100.toString()
    }

    private fun carrier(context: Context): String {
        val telephonyManager =
            context.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager?
        var operatorName = ""
        try {
            operatorName = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
                val subscriptionManager =
                    context.getSystemService(Context.TELEPHONY_SUBSCRIPTION_SERVICE) as SubscriptionManager?
                if (subscriptionManager != null && subscriptionManager.activeSubscriptionInfoCount > 0) {
                    subscriptionManager.activeSubscriptionInfoList[0].carrierName.toString()
                } else {
                    telephonyManager!!.simOperatorName
                }
            } else {
                telephonyManager!!.simOperatorName
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }

        return operatorName
    }
}